import android.app.AlertDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.shenshijia.R
import com.example.shenshijia.Word
//import kotlinx.android.synthetic.main.fragment_word_list.*

class WordListFragment : Fragment() {

    private val wordList = mutableListOf<Word>(
        Word("Hello"),
        Word("World"),
        Word("Kotlin")
    )

    private lateinit var adapter: WordAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_word_list2, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        adapter = WordAdapter(wordList) { word ->
            AlertDialog.Builder(context)
                .setTitle("Delete Word")
                .setMessage("Are you sure you want to delete ${word.name}?")
                .setPositiveButton("Delete") { _, _ ->
                    wordList.remove(word)
                    adapter.notifyDataSetChanged()
                }
                .setNegativeButton("Cancel", null)
                .create()
                .show()
        }

//        word_recycler_view.layoutManager = LinearLayoutManager(context)
//        word_recycler_view.adapter = adapter
    }
}

class WordAdapter(
    private val wordList: List<Word>,
    private val onLongClickListener: (Word) -> Unit
) : RecyclerView.Adapter<WordAdapter.WordViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WordViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(android.R.layout.simple_list_item_1, parent, false)
        return WordViewHolder(view)
    }

    override fun onBindViewHolder(holder: WordViewHolder, position: Int) {
        val word = wordList[position]
        holder.bind(word, onLongClickListener)
    }

    override fun getItemCount(): Int = wordList.size

    class WordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(word: Word, onLongClickListener: (Word) -> Unit) {
         //   itemView.textView.text = word.name
            itemView.setOnLongClickListener {
                onLongClickListener(word)
                true
            }
        }
    }
}